package com.employment.controller;

import com.employment.dto.JobPositionDTO;
import com.employment.dto.JobSearchDTO;
import com.employment.dto.Result;
import com.employment.entity.JobPosition;
import com.employment.security.UserPrincipal;
import com.employment.service.JobPositionService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 职位管理控制器
 * 
 * @author Employment System
 * @since 1.0.0
 */
@Tag(name = "职位管理", description = "职位管理相关接口")
@RestController
@RequestMapping("/api/jobs")
@RequiredArgsConstructor
public class JobPositionController {

    private final JobPositionService jobPositionService;

    @Operation(summary = "创建职位", description = "企业用户创建新职位")
    @PostMapping
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<JobPosition> createJob(@Validated @RequestBody JobPositionDTO jobPositionDTO,
                                       @AuthenticationPrincipal UserPrincipal userPrincipal) {
        JobPosition jobPosition = new JobPosition();
        BeanUtils.copyProperties(jobPositionDTO, jobPosition);
        jobPosition.setCreatedBy(userPrincipal.getUserId());
        
        boolean success = jobPositionService.createJob(jobPosition);
        if (success) {
            return Result.success("职位创建成功", jobPosition);
        }
        return Result.error("职位创建失败");
    }

    @Operation(summary = "更新职位", description = "更新职位信息")
    @PutMapping("/{jobId}")
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<Void> updateJob(@Parameter(description = "职位ID") @PathVariable Long jobId,
                                @Validated @RequestBody JobPositionDTO jobPositionDTO,
                                @AuthenticationPrincipal UserPrincipal userPrincipal) {
        JobPosition jobPosition = new JobPosition();
        BeanUtils.copyProperties(jobPositionDTO, jobPosition);
        jobPosition.setJobId(jobId);
        
        boolean success = jobPositionService.updateJob(jobPosition);
        if (success) {
            return Result.success("职位更新成功");
        }
        return Result.error("职位更新失败");
    }

    @Operation(summary = "删除职位", description = "删除指定职位")
    @DeleteMapping("/{jobId}")
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<Void> deleteJob(@Parameter(description = "职位ID") @PathVariable Long jobId,
                                @AuthenticationPrincipal UserPrincipal userPrincipal) {
        boolean success = jobPositionService.deleteJob(jobId);
        if (success) {
            return Result.success("职位删除成功");
        }
        return Result.error("职位删除失败");
    }

    @Operation(summary = "职位详情", description = "查询职位详细信息")
    @GetMapping("/{jobId}")
    public Result<JobPosition> getJobById(@Parameter(description = "职位ID") @PathVariable Long jobId) {
        JobPosition jobPosition = jobPositionService.getJobById(jobId);
        if (jobPosition != null) {
            // 增加浏览次数
            jobPositionService.increaseViewCount(jobId);
            return Result.success(jobPosition);
        }
        return Result.notFound();
    }

    @Operation(summary = "职位列表", description = "分页查询职位列表")
    @PostMapping("/search")
    public Result<Page<JobPosition>> searchJobs(@RequestBody JobSearchDTO searchDTO) {
        Page<JobPosition> page = new Page<>(searchDTO.getCurrent(), searchDTO.getSize());

        Page<JobPosition> result = jobPositionService.getJobPage(
                page,
                searchDTO.getKeyword(),
                searchDTO.getCategory(),
                searchDTO.getCity(),
                searchDTO.getSalaryMin(),
                searchDTO.getSalaryMax(),
                searchDTO.getWorkExperience(),
                searchDTO.getEducation(),
                searchDTO.getWorkType(),
                searchDTO.getStatus()
        );
        
        return Result.success(result);
    }

    @Operation(summary = "公司职位列表", description = "查询指定公司的职位列表")
    @GetMapping("/company/{companyId}")
    public Result<List<JobPosition>> getJobsByCompany(
            @Parameter(description = "公司ID") @PathVariable Long companyId,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        List<JobPosition> jobs = jobPositionService.getJobsByCompanyId(companyId, status);
        return Result.success(jobs);
    }

    @Operation(summary = "发布职位", description = "发布职位到招聘平台")
    @PostMapping("/{jobId}/publish")
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<Void> publishJob(@Parameter(description = "职位ID") @PathVariable Long jobId,
                                 @AuthenticationPrincipal UserPrincipal userPrincipal) {
        boolean success = jobPositionService.publishJob(jobId);
        if (success) {
            return Result.success("职位发布成功");
        }
        return Result.error("职位发布失败");
    }

    @Operation(summary = "下线职位", description = "将职位从招聘平台下线")
    @PostMapping("/{jobId}/offline")
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<Void> offlineJob(@Parameter(description = "职位ID") @PathVariable Long jobId,
                                 @AuthenticationPrincipal UserPrincipal userPrincipal) {
        boolean success = jobPositionService.offlineJob(jobId);
        if (success) {
            return Result.success("职位下线成功");
        }
        return Result.error("职位下线失败");
    }

    @Operation(summary = "热门职位", description = "查询热门职位列表")
    @GetMapping("/hot")
    public Result<List<JobPosition>> getHotJobs(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<JobPosition> hotJobs = jobPositionService.getHotJobs(limit);
        return Result.success(hotJobs);
    }

    @Operation(summary = "推荐职位", description = "根据用户求职意向推荐职位")
    @GetMapping("/recommend")
    @PreAuthorize("hasAnyRole('JOBSEEKER', 'ADMIN')")
    public Result<List<JobPosition>> getRecommendJobs(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        List<JobPosition> recommendJobs = jobPositionService.getRecommendJobs(userPrincipal.getUserId(), limit);
        return Result.success(recommendJobs);
    }

    @Operation(summary = "职位统计", description = "获取职位相关统计数据")
    @GetMapping("/stats")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<String>> getJobStats() {
        List<String> stats = jobPositionService.getJobStats();
        return Result.success(stats);
    }

    @Operation(summary = "批量更新状态", description = "批量更新职位状态")
    @PostMapping("/batch-status")
    @PreAuthorize("hasAnyRole('COMPANY', 'ADMIN')")
    public Result<Void> batchUpdateStatus(@RequestBody List<Long> jobIds,
                                        @RequestParam Integer status,
                                        @AuthenticationPrincipal UserPrincipal userPrincipal) {
        boolean success = jobPositionService.batchUpdateStatus(jobIds, status);
        if (success) {
            return Result.success("批量更新成功");
        }
        return Result.error("批量更新失败");
    }
}